import axios from 'axios'
import Cookie from 'js-cookie'
import {
  Message
} from 'element-ui'
import {
  serviceURL,
  u
} from '@/api/url.js'
// 创建axios实例
const service = axios.create({
  baseURL: serviceURL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    'Cache-Control': 'no-cache'
  }
})
// request拦截器
service.interceptors.request.use(config => {
  // let tokensInCookie = Cookie.get('userInfo')
  // let tokensInSession = sessionStorage.getItem('xl')
  // let tokensInCookie = sessionStorage.getItem('userInfo')
  let tokensInCookie = Cookie.get('userInfo')
  /*
   *cookie中的权限和sessionStorage中的权限, 
   *如果不相同, 跳到登录(同一浏览器, 用户a登录成功后, 
   *用户b在新的标签中登录, 当a用户界面发生请求后, 退出登录)
   */
  // if ((tokensInSession && tokensInCookie !== tokensInSession)) { 
  //     Message.info('权限失效, 请重新登录')
  //     sessionStorage.removeItem('xl')
  //     router.push({path: '/login'})
  //     window.location.reload()
  // }
  // 如果不是登录接口, 且session和cookie不存在, 返回登录
  if (!tokensInCookie && config.url !== u.login) {
    Message.info('权限失效, 请重新登录')
    // sessionStorage.removeItem('xl')
    // this.$router.push({path: '/login'})
    window.location.reload();
  }
  if (config.method === 'get') {
    config.params = {
      _t: Date.parse(new Date()),
      ...config.params
    }
  }
  return config
}, error => {
  console.log(error)
  // loadingInstance && loadingInstance.close()
  Promise.reject(error)
})

// 响应拦截器
// 响应拦截器
service.interceptors.response.use((response) => {
  // loadingInstance && loadingInstance.close()
  return response.data
}, (error) => {
  console.log('err' + error)
  // loadingInstance && loadingInstance.close()
  let errorInfo = '连接到服务器失败'
  if (error.response && error.response.status) {
    switch (error.response.status) {
      case 400:
        errorInfo = '错误请求'
        break
      case 401:
        errorInfo = '未授权或授权超时，请重新登录'
        break
      case 403:
        errorInfo = '拒绝访问'
        break
      case 404:
        errorInfo = '请求错误,未找到该资源'
        break
      case 405:
        errorInfo = '请求方法未允许'
        break
      case 408:
        errorInfo = '请求超时'
        break
      case 500:
        errorInfo = '服务器端出错'
        break
      case 501:
        errorInfo = '网络未实现'
        break
      case 502:
        errorInfo = '网络错误'
        break
      case 503:
        errorInfo = '服务不可用'
        break
      case 504:
        errorInfo = '网络超时'
        break
      case 505:
        errorInfo = 'http版本不支持该请求'
        break
      default:
        errorInfo = '连接到服务器失败'
    }
  }
  this.$message.error(errorInfo)
  return Promise.reject(error)
})

export default service